<?php

namespace addons\zzuser\controller\api;

use addons\zzuser\model\UserM;
use addons\zzuser\service\EncryptS;
use app\common\controller\Api;
use app\common\library\Sms;
use fast\Random;
use think\Db;
use think\Validate;

class Register extends Api
{
    protected $noNeedLogin = 'index';
    protected $noNeedRight = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'username'         => 'require|unique:user,username',
            'password'         => 'require',
            'password_confirm' => 'confirm:password',
            'mobile'           => 'min:1',
            'sms'              => 'min:1',
            'pid'              => 'min:1',
        ])) {
            $this->error($validate->getError());
        }

        $config = get_addon_config('zzuser');
        if ($config['register_sms_is'] == 'yes') {
            $mobile = input('mobile');
            $sms    = input('sms');
            if (!$mobile) {
                $this->error('error mobile');
            }
            if (!$sms || !Sms::check($mobile, $sms)) {
                $this->error('error sms');
            }
        }
        $pid = input('pid');
        if ($pid) {
            $fields = Db::query('show full columns from fa_user');
            $fields = array_column($fields, 'Field');
            if (!in_array('pid', $fields)) {
                Db::execute('alter table fa_user add column pid int default 0');
                $this->error('error pid init');
            }
            if (!UserM::find($pid)) {
                $this->error('error pid');
            }
        }
        $username = input('username');
        $password = input('password');
        $salt     = Random::alnum();
        $user     = UserM::create([
            'status'   => UserM::STATUS_NORMAL,
            'salt'     => $salt,
            'password' => EncryptS::password($password, $salt),
            'pid'      => $input['pid'] ?? null,
            'username' => $username,
            'nickname' => $username,
            'mobile'   => $mobile ?? '',
            'joinip'   => request()->ip(),
            'jointime' => time(),
        ]);
        $this->auth->direct($user['id']);
        $this->success('', [
            'token' => $this->auth->getToken(),
        ]);
    }
}
